<template>
  <div class="poinst-mall-list">
    <!-- 头部 -->
    <div class="app-main-content-box">
      <!-- 提示 -->
      <div v-if="!configForm.mallState" style="margin-bottom:10px">
        <el-tag type="warning">
          <i class="el-icon-warning" />&nbsp;积分商城功能已关闭, 你上架的商品顾客暂时不可以兑换, 如需要请先前往功能设置打开积分商城的开关！
        </el-tag>
      </div>
      <div class="flexRBC">
        <div class="list-search">
          <el-input
            v-model="filterForm.title"
            placeholder="请输入兑换内容"
            @keyup.enter.native="searchByKeyword"
          />
          <el-button
            :loading="searchLoading"
            type="primary"
            size="medium"
            round
            icon="el-icon-search"
            @click="searchByKeyword"
          >查 询</el-button>
        </div>
        <el-button
          v-if="!$store.getters.banBtnList.includes('BTN_ADD_POINTS_MALL_PRODUCT')"
          type="primary"
          size="medium"
          round
          @click="goPointsProductAdd"
        >增加积分商品</el-button>
      </div>

      <div class="content">
        <!-- 筛选 -->
        <!-- <div class="app-main-filter-collapse-box">
          <el-collapse>
            <el-collapse-item title="按条件筛选" name="1">
              <div>
                <el-form ref="ruleForm" label-width="120px" size="small">
                  <el-form-item label="筛选类型："/>
                  <el-form-item>
                    <el-button type="primary" round @click="submitForm('ruleForm')">筛选</el-button>
                    <el-button round @click="resetForm('ruleForm')">重置</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>-->
        <!-- 表格内容 -->
        <div class="list-table">
          <el-table
            v-loading="tableLoading"
            :data="list"
            border
            stripe
            style="width: 100%"
            empty-text="暂无数据"
          >
            <el-table-column prop="title" label="兑换内容" fixed />
            <el-table-column prop="coverImage" label="兑换图" fixed>
              <template v-if="scope.row.coverImage" slot-scope="scope">
                <img class="table-avatar" :src="fileBaseUrl+scope.row.coverImage" alt>
              </template>
            </el-table-column>
            <el-table-column prop="productType" label="类型" fixed>
              <template slot-scope="scope">
                <span class="app-text-color-primary">{{ productTypeOptions[scope.row.productType] }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="productPoint" label="兑换积分">
              <template slot-scope="scope">
                <span>{{ scope.row.productPoint|parseNumberToThousands(0,false) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="salesNum" label="已兑换">
              <template slot-scope="scope">
                <span>{{ scope.row.salesNum|parseNumberToThousands(0,false) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="usableQty" label="剩余库存">
              <template slot-scope="scope">
                <span v-if="scope.row.usableQty==null">不限</span>
                <span v-else>{{ scope.row.usableQty|parseNumberToThousands(0,false) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="可兑换时间" width="200">
              <template slot-scope="scope">
                <span>开始：{{ scope.row.onlineTime }}</span>
                <span>过期：{{ scope.row.offlineTime }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="180">
              <template slot-scope="scope">
                <template v-if="isEditSort&&scope.row.id==sortForm.id">
                  <el-input
                    v-model.number="sortForm.sort"
                    class="ranking-input"
                    maxlength="5"
                    size="mini"
                    @keyup.enter.native="confirmEditSort(scope.row)"
                  />
                </template>
                <span v-else>{{ scope.row.sort }}</span>
                <el-button
                  v-if="isEditSort&&scope.row.id==sortForm.id"
                  type="text"
                  size="small"
                  @click="confirmEditSort(scope.row)"
                >确定</el-button>
                <el-button
                  v-if="isEditSort&&scope.row.id==sortForm.id"
                  type="text"
                  @click="cancelEditSort(scope.row)"
                >取消</el-button>
                <el-button
                  v-else-if="!$store.getters.banBtnList.includes('BTN_POINTS_MALL_PRODUCT_EDIT')"
                  type="text"
                  size="small"
                  icon="el-icon-edit"
                  @click="editRanking(scope.row,scope.$index)"
                >排序</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="state" label="上架状态" width="120">
              <template slot-scope="scope">
                <!-- 已过期 -->
                <span v-if="scope.row.expire">已过期</span>
                <span
                  v-else
                  :class="statusTableColorOptions[scope.row.state]"
                >{{ stateOptions[scope.row.state] }}</span>
              </template>
            </el-table-column>
            <el-table-column
              v-if="!$store.getters.banBtnList.includes('BTN_POINTS_MALL_PRODUCT_EDIT')"
              label="操作"
              width="130"
              fixed="right"
            >
              <template slot-scope="scope">
				<el-button
				  v-if="!scope.row.expire&&!$store.getters.banBtnList.includes('BTN_CHANGE_POINTS_MALL_PRODUCT_STATUS')"
				  type="text"
				  @click="changeState(scope.row)"
				>{{ scope.row.state===1?'下架':'上架' }}</el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="goPointsProductEdit(scope.$index, scope.row)"
                >编辑</el-button>
                <el-button
                  type="text"
                  size="small"
                  @click="delPointsProduct(scope.$index, scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <pagination-direction
            v-if="paginationConfig.total!==0"
            :config="paginationConfig"
            @sizeschange="sizesChange"
            @pagechange="pageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { validateCustomPositiveInt } from '@/utils/validate'
import { getProductList, changeProductState, modifySort, getPointsMallConfig, remove } from '@/api/points'
export default {
  props: {
    tabName: {
      type: String,
      require: true
    }
  },
  data() {
    return {
      // 修改状态弹框
      disaBulletBox: false,
      // 配置
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      productTypeOptions: ['优惠券', '实物', '礼品'],
      stateOptions: ['已下架', '已上架', '已过期'],
      statusTableColorOptions: [
        'app-text-color-danger',
        'app-text-color-success',
        ''
      ],
      // 状态
      tableLoading: false, // 表格loading
      searchLoading: false, // 搜索loading
      // 数据
      isEditSort: '', // 是否激活排序
      sortForm: {
        id: '',
        sort: ''
      },
      configForm: {
        mallState: 1
      },
      filterForm: {
        title: ''
      },
      list: [] // 表格数据
    }
  },
  watch: {
    tabName(val) {
      if (val === 'mall') {
        this.initConfig()
        this.initData()
      }
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl'])
  },
  mounted() {
    this.initConfig()
    this.initData()
  },
  methods: {
    /**
       * 获取数据
       */
    // 获取商城配置
    initConfig() {
      getPointsMallConfig().then(res => {
        this.configForm = res.data
      })
    },

    // 获取数据
    initData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      // 加入page
      this.filterForm.pageNum = page
      this.filterForm.pageSize = pageSize
      const params = Object.assign({}, this.filterForm)
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      this.tableLoading = true
      getProductList(params)
        .then(res => {
          this.list = res.data.list
          this.paginationConfig.total = res.data.total
          this.paginationConfig.page = res.data.pageNum
        })
        .finally(() => {
          this.tableLoading = false
          this.searchLoading = false
        })
    },

    // 分页sizes改变
    sizesChange() {
      this.initData()
    },

    // 分页page改变
    pageChange() {
      this.initData()
    },

    /**
       * 按钮组
       */
    // 点击搜索
    searchByKeyword() {
      this.searchLoading = true
      this.initData(1)
    },

    // 排序
    editRanking(row, index) {
      this.sortForm = Object.assign({}, row)
      this.isEditSort = true
    },

    // 取消排序
    cancelEditSort(row) {
      this.isEditSort = false
    },

    // 确定排序
    confirmEditSort(row) {
      if (!validateCustomPositiveInt(this.sortForm.sort, 5, [0])) {
        this.$message.error('请输入0或正整数')
        return
      } else if (row.sort == this.sortForm.sort) {
        this.isEditSort = false
        return
      }
      const params = {}
      params.sort = this.sortForm.sort
      params.productId = this.sortForm.id
      this.tableLoading = true
      modifySort(params)
        .then(res => {
          this.isEditSort = false
          this.$notify({
            title: '成功',
            message: '排序成功',
            type: 'success',
            duration: 2000,
            offset: 40
          })
          this.initData()
        })
        .catch(err => {})
        .finally(() => {
          this.tableLoading = false
        })
    },

    // 点击新增
    goPointsProductAdd() {
      this.$router.push({
        name: 'VipPointsProductAdd'
      })
    },

    // 跳转编辑
    goPointsProductEdit(index, row) {
      this.$router.push({
        name: 'VipPointsProductEdit',
        params: { id: row.id }
      })
    },
	// 删除
	delPointsProduct(index, row){
		this.$confirm('删除积分商品后将不可恢复，是否确定删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
			remove({productId:row.id}).then(res => {
				this.$message({
				  type: 'success',
				  message: '删除成功!'
				});
				this.initData()
			})
        }).catch(() => {});
	},

    // 筛选
    submitForm(formName) {
      this.initData(1)
    },

    // 筛选重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },

    // 上下架
    changeState(row) {
      this.$confirm(
        `是否${row.state === 0 ? '上架' : '下架'}：${row.title}`,
        '温馨提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          roundButton: true
        }
      )
        .then(() => {
          this.tableLoading = true
          // 发送修改状态请求
          const params = {}
          params.productId = row.id
          params.state = row.state === 1 ? 0 : 1
          changeProductState(params)
            .then(res => {
              row.state = params.state
              this.$notify({
                title: '成功',
                message: `${row.state === 1 ? '上架' : '下架'}成功`,
                type: 'success',
                duration: 2000,
                offset: 40
              })
            })
            .finally(() => {
              this.tableLoading = false
            })
        })
        .catch(() => {})
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  /* 搜索*/
  .list-search {
    .el-input {
      width: 400px;
      margin-right: 10px;
    }
  }
  /* 表格 */
  .content {
    margin-top: 10px;
    .table-avatar {
      vertical-align: middle;
      width: 30px;
      height: 30px;
      border: 1px solid #e7e7e7;
    }
    /* 排序相关 */
    .ranking-input {
      width: 70px;
    }
  }
</style>
